package com.linfeng.component.common.tools;

import cn.hutool.core.date.DateUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.JWTValidator;
import com.linfeng.component.common.exception.CustomException;
import com.linfeng.component.common.exception.CustomExceptionCode;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class TokenTools {

    private static final String TOKEN_SINGER = "linfeng";

    // 默认有效期7天
    private static final Long EXPIRES = 60 * 60 * 1000 * 24 * 7L;

    public static String createToken(Long userId) {

        return createToken(userId, EXPIRES);
    }

    public static String createToken(Long userId, Long expires) {

        Map<String, Object> payload = new HashMap<>();
        payload.put("userId", userId);
        payload.put(JWTPayload.EXPIRES_AT, DateUtil.date(System.currentTimeMillis() + expires));

        return JWTUtil.createToken(payload, TOKEN_SINGER.getBytes(StandardCharsets.UTF_8));
    }

    public static boolean verify(String token) {

        boolean verify = JWTUtil.verify(token, TOKEN_SINGER.getBytes(StandardCharsets.UTF_8));

        if (verify) {
            try {
                JWTValidator.of(token).validateDate();
            } catch (Exception e) {
                throw new CustomException(CustomExceptionCode.TOKEN_VERIFY);
            }
        }

        return verify;
    }

//    public static Long parseToken(String token) {
//
//        JWT jwt = JWTUtil.parseToken(token);
//
//        return (Long) jwt.getPayload("userId");
//    }

    public static JWTPayload parseToken(String token) {

        JWT jwt = JWTUtil.parseToken(token);

        return jwt.getPayload();
    }

    public static String getUserName(String token) {

        return (String) parseToken(token).getClaim("user_name");
    }
}
